﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using ModelLayer;
// services
using TicketCtrlService;
using ReservationCtrlService;

public partial class User_Scripts_reserve : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}

	public bool Reserve(NameValueCollection GET)
	{
		int schedId = Int32.Parse(GET.GetValues("schedid")[0]);
		int seatId = Int32.Parse(GET.GetValues("seatid")[0]);

		TicketCtrlClient ticketService = new TicketCtrlClient();
		int ticketId = ticketService.addTicket(schedId, seatId);
		if (ticketId == -1)
			return false;

		Ticket ticket = ticketService.getTicketById(ticketId);
		ticketService.Close();
		if (ticket == null)
			return false;

		string[] name = GET.GetValues("name");
		string[] phone = GET.GetValues("phone");
		if (name != null && phone != null)
		{
			ReservationCtrlClient reservationService = new ReservationCtrlClient();
			int result = reservationService.addReservation(name[0], phone[0], ticket);
			reservationService.Close();
			if (result == -1)
				return false;
		}

		return true;
	}

	public bool Unreserve(NameValueCollection GET)
	{
		int schedId = Int32.Parse(GET.GetValues("schedid")[0]);
		int seatId = Int32.Parse(GET.GetValues("seatid")[0]);

		TicketCtrlClient ticketService = new TicketCtrlClient();
		Ticket[] tickets = ticketService.getTicketsBySchedule(schedId);

		foreach (Ticket ticket in tickets)
			if (ticket.seat.id == seatId)
			{
				bool result = ticketService.removeTicket(ticket.id);
				ticketService.Close();

				ReservationCtrlClient reservationService = new ReservationCtrlClient();
				Reservation reservation = reservationService.getReservationByTicket(ticket.id);
				if (result && reservation != null)
					result = reservationService.removeReservation(reservation.Id);

				return result;
			}

		return false;
	}
}